<?php

namespace App\Console\Commands;

use App\Helpers\Logger\SLogger;
use App\Models\Orm\DataProductApplyLog;
use App\Models\Orm\Deliver;
use Illuminate\Console\Command;
use App\Helpers\Http\HttpClient;

class DataDeliveryProductCount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'DataDeliveryProductCount {date?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '渠道产品总览统计脚本';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private $date;

    /**
     * 预定义要插入count表的数据容器
     * @var array
     */
    private $dataList = [];

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        #记录开始统计日志
        SLogger::getStream()->info('启动' . __CLASS__);

        // 要统计的日期,默认昨天
        $date = date("Y-m-d", strtotime("-1 day"));

        $inputDate = $this->argument('date');


        if ($inputDate) {
            $patten = '/^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/';
            if (!preg_match($patten, $inputDate)) {
                echo "您输入的日期格式不正确!\n";
                SLogger::getStream()->info('您输入的日期格式不正确!');
                return false;
            }
            $date = $inputDate;
        }

        // 设置查询日期
        $this->setDate($date);

        // 处理申请按钮点击量
        $this->handleApplyLogs();

        echo "执行成功!\n";

    }


    /**
     * 将时间赋值，默认是昨天
     * @param $date
     * @return mixed
     */
    private function setDate($date)
    {
        if (!$this->date) {
            $this->date = $date;
        }
        return $this->date;
    }


    /**
     * 处理渠道对应产品的点击次数和点击人数
     */
    private function handleApplyLogs()
    {
        //查询出所有的开放渠道
        $channels = Deliver::where('status',1)->get()->toArray();

        foreach($channels as $channel) {

            $channel_id = $channel['id'];

            //获取该渠道下以产品id分组的渠道产品日志数据
            $result = $this->getDayApplyLogs($channel_id);


            foreach($result as $product)
            {
                $start = $this->date . ' 00:00:00';
                $end   = $this->date . ' 24:00:00';

                //符合条件的所有log
                $logs_all = DataProductApplyLog::where('channel',$channel_id)
                    ->where('product_id',$product['product_id'])
                    ->where('create_at', '>', $start)
                    ->where('create_at', '<=', $end)
                    ->get()->toArray();

                $applyCount = count($logs_all);

                //符合条件的所有log通过userId进行分组
                $logs_group_user = DataProductApplyLog::where('channel',$channel_id)
                    ->where('product_id',$product['product_id'])
                    ->where('create_at', '>', $start)
                    ->where('create_at', '<=', $end)
                    ->groupBy('create_ip')
                    ->get()
                    ->toArray();
                $logs_user_apply = DataProductApplyLog::where('channel',$channel_id)
                    ->where('create_at', '>', $start)
                    ->where('create_at', '<=', $end)
                    ->groupBy('create_ip')
                    ->get()
                    ->toArray();
                $applyUserId = count($logs_user_apply);

//                // 区分点击人数中现金贷已注册用户
                $awuser_total = 0;
                $xduser_total = 0;
//                foreach ($logs_group_user as $k => $v)
//                {
//                    //请求现金贷那边的接口，判断点击用户是否注册现金贷
//                    $url     =  "http://www.shoujijiekuan.com//Web/CheckTel.aspx?CellNo=".$v['userphone'];
//                    $promise = HttpClient::i()->request('GET', $url);
//                    $result  = $promise->getBody()->getContents();
//                    if($result == 0)
//                    {
//                        $awuser_total += 1;
//                    }else{
//                        $xduser_total += 1;
//                    }
//                }

                $applyUserCount = count($logs_group_user);

                //插入统计表的数组
                $data =
                    [
                        'product_id'    => $product['product_id'],
                        'product_name'  => $product['product_name'],
                        'channel_id'    => $product['channel'],
                        'apply_total'   => $applyCount,
                        'user_total'    => $applyUserCount,
                        'awuser_total'  => $awuser_total,
                        'xduser_total'  => $xduser_total,
                        'create_date'   => $this->date,
                        'total_user_id' => $applyUserId,
                        'status'        => 1,
                    ];

                $re = $this->insertDataDeliverProductCount($data);
                if(!$re)
                {
                    SLogger::getStream()->error($this->date.' 渠道号为:'.$product['channel'] .'下产品id为'.$product['product_name'] .'统计失败！');
                }
                SLogger::getStream()->info($this->date.' 渠道号为:'.$product['channel'] .'下产品id为'.$product['product_name'] .'统计成功！');


            }

        }

    }


    /**
     * 获取某一天某一个渠道所有产品
     */
    private function getDayApplyLogs($channel_id)
    {

        $start = $this->date . ' 00:00:00';
        $end   = $this->date . ' 24:00:00';

        //按照时间查询出某个渠道下产品的某一天的数据
        $result = DataProductApplyLog::select([
            'product_id as product_id',
            'product_name as product_name',
            'channel',
            'user_id',
            'product.product_logo',
        ])
            ->leftjoin('product', 'product.id', '=', 'data_product_apply_log.product_id')
            ->where('channel',$channel_id)
            ->where('create_at', '>', $start)
            ->where('create_at', '<=', $end)
            ->groupBy('product_id')
            ->get()
            ->toArray();
        return $result ? : [];

    }


    private function insertDataDeliverProductCount($data)
    {
        $where = [
                    'channel_id' =>$data['channel_id'],
                    'product_id' => $data['product_id'],
                    'create_date'=> $data['create_date']
                 ];
        return \App\Models\Orm\DataDeliveryProductCount::updateOrCreate($where, $data) ? true : false;
    }
}
